package com.httpserver.one;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;

/**
 *@project:HttpServerDemo
 *@author   wuhn
 *@version  1.0
 *@createTime:2017年10月18日 下午12:31:30
 *@description: 返回HTTP 数据流，按照HTTP返回请求文件
 */
public class Answer {
	
	public static final String ROOT="c:/";
	
	OutputStream  out =null;

	public Answer(OutputStream out) {
		super();
		this.out = out;
	}
	
	/**
	 * 该方法作用是返回HTTP数据流
	 * @throws IOException 
	 */
	public void send(String pageFile) throws IOException{
		byte[]  bytes =new byte[2048];
		FileInputStream  fis=null;
		final File file = new File(ROOT+pageFile);
		if(file.exists()){
				fis =new FileInputStream(file);
				final int ch = fis.read(bytes,0,2048);
				final String sBody = new String(bytes);
				String sendMessage="HTTP /1.1 200 OK \r\n"+
									"Content-Type: text/html \r\n"+
									"Content-Length: "+ch+"\r\n"+
									"\r\n"+sBody;
			//输出文件
				out.write(sendMessage.getBytes());
		}else{
			String errorMessage="HTTP /1.1 404 File Not Found \r\n"+
								"Content-Type: text/html \r\n"+
								"Content-Length: 23\r\n"+
								"\r\n"+
								"<h1>File Not Found</h1>";
			out.write(errorMessage.getBytes());
		}
		out.flush();
		out.close();
		if(fis != null){
			fis.close();
		}
	}
	
}
